<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: 'e1b93e9730d1a02819c9d41e30a47da5',
        }
    </script>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=97e1969986cfdad21dd89813a23d5a28">
    </script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body,
        #container {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="container"></div>

    <script>
        // https://lbs.amap.com/api/jsapi-v2/guide/geometry/geometry
        let map = new AMap.Map('container', {
            center: [112.54, 37.85],
            zoom: 13,
            viewMode: '2D',
        })

        // 37.845798
        // 112.551845
        // 37.839562
        // 112.586177
        map.on('click', (event) => {
            console.log(event);
        })

        var m1 = new AMap.Marker({
            map: map,
            draggable: true,
            position: new AMap.LngLat(112.551845, 37.845798)
        })

        var m2 = new AMap.Marker({
            map: map,
            draggable: true,
            position: new AMap.LngLat(112.586177, 37.839562)
        })

        // 让地图根据覆盖物 调整显示区域 自适应
        map.setFitView()
        var line = new AMap.Polyline({
            strokeColor: 'skyblue',
            isOutline: true,
            outerlineColor: '#fff'
        })

        line.setMap(map)

        var text = new AMap.Text({
            text: '',
            style: {
                'background-color': 'skyblue',
                'border-color': 'red',
                'font-size': '16px'
            }
        })

        text.setMap(map)

        function compute() {
            var p1 = m1.getPosition()
            var p2 = m2.getPosition()

            var textPos = p1.divideBy(2).add(p2.divideBy(2))
            var distance = Math.round(p1.distance(p2))
            var path = [p1, p2]
            line.setPath(path)
            text.setText('距离为：' + distance + '米')
            text.setPosition(textPos)
        }
        compute()
        m1.on('dragging', compute)
        m2.on('dragging', compute)
    </script>
</body>

</html>